#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import os
import xml
import xml.etree.ElementTree as ET
from MOMA.MOMA_V1.uitls.re.reg import Reg


class Xml:
    global banner_list
    banner_list = []

    def __init__(self, recv: tuple):
        self.recv = recv

    def xml_file(self):
        """
        遍历目录查找xml文件
        :return:
        """
        file_list = os.listdir('MOMA_V1/data/xml/')
        for file in file_list:
            if file.split('.')[1] == 'xml':
                yield file

    def xml_root(self, file_list) -> list | None:
        """
        遍历出xml根节点的正则
        :param file_list:
        :return:
        """
        for file in file_list:
            tree = ET.parse("MOMA_V1/data/xml/{}".format(file))
            roots = tree.getroot()
            for root in roots:
                if Reg.run_re(root.attrib['value'], self.recv[1]):
                    return self.banner_detail(root, self.recv[0])

    def banner_detail(self, xml_obj: xml.etree.ElementTree.Element, port: int) -> list | None:
        """
        利用xml里的正则进行判断
        :param port:
        :param xml_obj:
        :return:
        """
        return {port: i.attrib for i in xml_obj.iter('info') if (port, i.attrib)}
